import {
  login,
  register,
  verifyLogin,
  silentLogin
} from "@/api/login/index.js";
import globalSite from "@/config/globalSite";
import {
  setAuthToken,
  setAccessToken,
  setUserInfo,
  setCompanyInfo,
  getAuthToken,
  getAccessToken
} from "@/util/auth";
import instance from "@/main";
import { getUserAuthstate } from "@/api/certify";
import authDict from "@/dict/auth";

const user = {
  state: {
    isLogin: false, // 是否已登录
    isAdmin: false, // 是否管理员以上
    userData: null, // 个人信息
    company: null, // 企业信息
    accessToken: null, //
    authToken: null,
    authState: null, // 身份认证状态
    activate: false // 是否需要激活用户
  },
  mutations: {
    SET_LOGIN: (state, val) => {
      state.isLogin = val;
    },
    SET_TOKEN: (state, token) => {
      state.accessToken = token;
    },
    SET_AUTH_TOKEN: (state, authToken) => {
      state.authToken = authToken;
    },
    SET_ISADMIN: (state, val) => {
      state.isAdmin = val;
    },
    SET_USER: (state, userInfo) => {
      state.userData = userInfo;
    },
    SET_AUTH_STATE: (state, val) => {
      state.authState = val;
    },
    SET_COMPANY: (state, company) => {
      state.company = company;
    },
    // 设置激活状态
    SET_ACTIVATE: (state, val) => {
      state.activate = val;
      if (val && instance.$route.path !== "/activate/personal") {
        instance.$error({
          title: "用户未激活",
          content:
            "因商城系统升级，用户需重新激活以便确认用户本人亲自操作，谢谢配合！",
          okText: "立即激活",
          keyboard: false,
          onOk() {
            instance.$router.push({ name: "activatePersonal" });
          }
        });
      }
    }
  },
  actions: {
    // 查询并更新用户激活状态
    updateActivate({ commit }) {
      getUserAuthstate().then(res => {
        commit(
          "SET_ACTIVATE",
          res.authState === authDict.inactive_personal.value ? true : false
        );
      });
    },
    // 注册并登录
    register({ dispatch }, data) {
      return new Promise((resolve, reject) => {
        register(data)
          .then(res => {
            let resData = res;
            resolve(res);
            if (instance.$route.name === "spotmall")
              dispatch("setLoginInfo", resData);
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    // 普通登录
    login({ dispatch }, data) {
      return new Promise((resolve, reject) => {
        let params = {
          ...data
        };
        // 查询是否有设备码，有则带上
        let authToken = JSON.parse(
          localStorage.getItem(globalSite.authToken + data.phone)
        );
        if (authToken) params.authToken = authToken;
        login(params)
          .then(res => {
            let resData = res;
            resolve(res);
            if (instance.$route.name === "spotmall")
              dispatch("setLoginInfo", resData);
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    // 短信验证登录
    verifyLogin({ dispatch }, data) {
      return new Promise((resolve, reject) => {
        verifyLogin(data)
          .then(res => {
            let resData = res;
            resolve(res);
            if (instance.$route.name === "spotmall")
              dispatch("setLoginInfo", resData);
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    // 静默登录
    silentLogin({ dispatch }, data) {
      return new Promise((resolve, reject) => {
        let params;
        // 没有传参则用默认值
        if (data) {
          params = data;
        } else {
          params = {
            accessToken: getAccessToken(),
            authToken: getAuthToken(),
            terminalFlag: 4
          };
        }
        silentLogin(params)
          .then(res => {
            let resData = res;
            dispatch("setLoginInfo", resData).then(r => {
              resolve(r);
            });
          })
          .catch(err => {
            dispatch("logout");
            reject(err);
          });
      });
    },
    // 存储登录后的用户信息并建立ws
    setLoginInfo({ commit, dispatch }, resData) {
      return new Promise((resolve, reject) => {
        let access_token = globalSite.accessToken + resData.user.phone;
        let auth_token = globalSite.authToken + resData.user.phone;
        let userInfo = {
          ...resData.user,
          roleId: resData.roleId,
          roleName: resData.roleName
        };
        commit("SET_LOGIN", true);
        commit("SET_TOKEN", resData[globalSite.accessToken]);
        commit("SET_AUTH_TOKEN", resData[globalSite.authToken]);
        commit("SET_ISADMIN", resData.isAdmin);
        commit("SET_USER", userInfo);
        commit("SET_AUTH_STATE", resData.authState);
        commit("SET_COMPANY", resData.company);
        setAccessToken(access_token, resData[globalSite.accessToken]);
        setAuthToken(auth_token, resData[globalSite.authToken]);
        setUserInfo(globalSite.userInfo, userInfo);
        setCompanyInfo(globalSite.companyInfo, resData.company);
        localStorage.setItem(globalSite.loginPhone, resData.user.phone);
        dispatch("resetReconnectNum");
        dispatch("createLoginWs")
          .then(res => {
            dispatch("updateActivate");
            resolve(res);
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    // 设置已登录标识
    setIsLogin({ commit }, data) {
      commit("SET_LOGIN", data);
    },
    // 登出
    logout({ commit, dispatch, state }, data) {
      return new Promise(resolve => {
        let userPhone = state.userData && state.userData.phone;
        // 重置路由
        // resetRouter();
        dispatch("resetRouter");
        // 清除用户信息、路由信息、权限信息
        commit("SET_USER", null);
        commit("SET_AUTH_STATE", null);
        commit("SET_COMPANY", null);
        commit("SET_TOKEN", null);
        commit("SET_AUTH_TOKEN", null);
        commit("SET_INIT", false);
        commit("SET_LOGIN", false);
        if (data && data === 4003)
          localStorage.removeItem(globalSite.authToken + userPhone); // 同设备登录下线后，删除authToken
        localStorage.removeItem(globalSite.accessToken + userPhone);
        localStorage.removeItem(globalSite.userInfo);
        localStorage.removeItem(globalSite.companyInfo);
        localStorage.removeItem(globalSite.loginPhone);
        // localStorage.removeItem("authToken"); // authToken设备码不需要清除，下次登录时需要带上，视为受信任的设备
        localStorage.removeItem("asyncRouter");
        dispatch("closeLoginWs");
        resolve();
      });
    }
  }
};

export default user;
